<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.trainOrderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="结算类型" prop="checkoutType">
        <el-select
          v-model="queryParams.checkoutType"
          placeholder="请选择结算类型"
          clearable
          class="!w-240px"
        >
          <el-option label="线下结算" value="OFFLINE" />
          <el-option label="微信转账" value="WXQB" />
          <el-option label="微信分账" value="WXFZ" />
        </el-select>
      </el-form-item>
      <el-form-item label="结算状态" prop="checkoutStatus">
        <el-select
          v-model="queryParams.checkoutStatus"
          placeholder="请选择结算状态"
          clearable
          class="!w-240px"
        >
          <el-option label="未结算" :value="0" />
          <el-option label="已结算" :value="1" />
          <el-option label="全部" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['sale:checkout-order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="订单 id" align="center" width="200" prop="trainOrderId" />
      <el-table-column label="用户昵称/头像" align="center" prop="nickName">
        <template #default="scope">
          <div class="w-full flex justify-center items-center">
            <img class="w-10 h-10 rounded-full" :src="scope.row.avatar" />
            <div class="ml-3 text-base">{{ scope.row.nickname }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="用户手机号" align="center" prop="nickName">
        <template #default="scope">
          <!-- <div class="ml-3 text-base">{{ scope.row.nickname }}</div> -->
          <div v-if="scope.row.mobile" style="font-size: 12px; color: #cccccc">{{
            scope.row.mobile
          }}</div>
          <div v-else style="font-size: 12px; color: #cccccc">未设置手机号</div>
        </template>
      </el-table-column>

      <el-table-column label="结算类型" align="center" prop="checkoutType">
        <template #default="scope">
          <el-tag class="ml-2" :type="checkoutOrderTypeFormatter(scope.row.checkoutType).type">{{
            checkoutOrderTypeFormatter(scope.row.checkoutType).text
          }}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="结算路径" align="center" prop="checkoutPath">
        <template #default="scope">
          <el-tag class="ml-2" :type="checkoutOrderPathFormatter(scope.row.checkoutPath).type">{{
            checkoutOrderPathFormatter(scope.row.checkoutPath).text
          }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column
        label="结算金额(元)"
        align="center"
        prop="checkoutAmount"
        :formatter="amountFormatter"
      />
      <!-- <el-table-column label="结算延迟(天)" align="center" prop="checkoutDelay" /> -->
      <el-table-column label="结算状态" align="center" prop="status">
        <template #default="scope">
          <el-tag class="ml-2" :type="statusFormatter(scope.row.status).type">{{
            statusFormatter(scope.row.status).text
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="结算时间"
        align="center"
        prop="checkoutTime"
        width="200"
        :formatter="dateFormatter"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="200"
        :formatter="dateFormatter"
      />
      <el-table-column label="操作" align="center" fixed="right" width="180">
        <template #default="scope">
          <el-button
            link
            :type="
              scope.row.status === CheckoutOrderApi.CheckoutStatus.UNCHECKOUT ? 'primary' : 'info'
            "
            v-hasPermi="['train:checkout-order:update']"
            @click="handleCheckout(scope.row.id, scope.row.status)"
          >
            {{
              scope.row.status === CheckoutOrderApi.CheckoutStatus.UNCHECKOUT
                ? '手动结算'
                : '取消结算'
            }}
          </el-button>
          <!-- <el-button
            link
            type="danger"
            v-hasPermi="['train:checkout-order:delete']"
            @click="handleDelete(scope.row.clientUserId)"
          >
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CheckoutOrderForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts" name="EnrollClue">
import * as CheckoutOrderApi from '@/api/promotion/checkout-order/index'
import CheckoutOrderForm from './checkout-order-form.vue'
import { dateFormatter } from '@/utils/formatTime'
import { statusDict, checkoutPathDict, checkoutTypeDict } from './common'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<CheckoutOrderApi.CheckoutOrderVO[]>([]) // 列表的数据
const queryParams = reactive<PageParam & CheckoutOrderApi.CheckoutOrderQuery>({
  pageNo: 1,
  pageSize: 10,
  trainOrderNo: undefined,
  checkoutType: undefined,
  checkoutStatus: undefined
})

const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CheckoutOrderApi.getPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: string) => {
  formRef.value.open(type, id)
}

/** 手动结算 */
const handleCheckout = async (
  id: string,
  currentCheckoutStatus: CheckoutOrderApi.CheckoutStatus
) => {
  const targetStatus =
    currentCheckoutStatus === CheckoutOrderApi.CheckoutStatus.UNCHECKOUT
      ? CheckoutOrderApi.CheckoutStatus.CHECKOUT
      : CheckoutOrderApi.CheckoutStatus.UNCHECKOUT

  try {
    await message.confirm(
      `确认${targetStatus === CheckoutOrderApi.CheckoutStatus.CHECKOUT ? '结算' : '取消结算'}吗？`
    )
    await CheckoutOrderApi.updateStatusById(id, targetStatus)
    message.success('结算成功')
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CheckoutOrderApi.deleteById(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 分账类型格式化 */
const checkoutOrderTypeFormatter = (val: CheckoutOrderApi.CheckoutType) => {
  const type = checkoutTypeDict.find((item) => item.value === val)
  return {
    type: type?.type,
    text: type?.label
  }
}

/** 分账路径格式化 */
const checkoutOrderPathFormatter = (val: CheckoutOrderApi.CheckoutPath) => {
  const path = checkoutPathDict.find((item) => item.value === val)
  return {
    type: path?.type,
    text: path?.label
  }
}

/** 状态格式化 */
const statusFormatter = (val: CheckoutOrderApi.CheckoutStatus) => {
  const status = statusDict.find((item) => item.value === val)
  return {
    type: status?.type,
    text: status?.label
  }
}

/** 金额格式化 */
const amountFormatter = (_row, _column, value, _index) => {
  return value / 100 + '元'
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
